package org.tio.examples.im.common.json;

import java.util.HashSet;
import java.util.Set;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.PropertyPreFilter;

/*
 * Copyright 1999-2101 Alibaba Group.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class SimplePropertyPreFilter implements PropertyPreFilter
{

	private final Class<?> clazz;
	private final Set<String> excludes = new HashSet<String>();
	private final Set<String> includes = new HashSet<String>();

	public SimplePropertyPreFilter(Class<?> clazz, String... properties)
	{
		super();
		this.clazz = clazz;
		for (String item : properties)
		{
			if (item != null)
			{
				this.includes.add(item);
			}
		}
	}

	public SimplePropertyPreFilter(String... properties)
	{
		this(null, properties);
	}

	@Override
	public boolean apply(JSONSerializer serializer, Object source, String name)
	{
		if (source == null)
		{
			return true;
		}

		if (clazz != null && !clazz.isInstance(source))
		{
			return true;
		}

		if (this.excludes.contains(name))
		{
			return false;
		}

		if (includes.size() == 0 || includes.contains(name))
		{
			return true;
		}

		return false;
	}

	public Class<?> getClazz()
	{
		return clazz;
	}

	public Set<String> getExcludes()
	{
		return excludes;
	}

	public Set<String> getIncludes()
	{
		return includes;
	}

}
